package cn.sell.mbg.sys.file.service.impl;

import cn.sell.comm.base.MySqlCrudServiceImpl;
import cn.sell.comm.util.DateUtil;
import cn.sell.mbg.sys.file.SysFile;
import cn.sell.mbg.sys.file.bean.CopyFile;
import cn.sell.mbg.sys.file.mapper.SysFileMapper;
import cn.sell.mbg.sys.file.service.SysFileService;
import com.google.common.collect.Lists;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@Log4j2
@Service
@Transactional
public class SysFileServiceImpl
        extends MySqlCrudServiceImpl<SysFile, Long>
        implements SysFileService {

    @Autowired
    private SysFileMapper sysFileMapper;

    /**
     * @param request
     * @param filePath     文件路径
     * @throws Exception
     * @return
     */
    @Override
    public List<SysFile> uploadFile(HttpServletRequest request, String filePath) throws Exception {
        Assert.notNull(filePath, "filePath is not null；[文件路径不能为空]");
        long startTime = System.currentTimeMillis();
        if (request instanceof MultipartHttpServletRequest) {
            List<SysFile> files = new ArrayList<>();
            Map<String, MultipartFile> fileMap = ((MultipartHttpServletRequest) request).getFileMap();
            for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
                log.info("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                MultipartFile multipartFile = entry.getValue();
                log.info("文件大小， 标记 {}",multipartFile.getSize());
                File newFile = this.createFile(multipartFile, filePath);
                files.add(saveMassage(newFile,entry.getKey()));
                long endTime = System.currentTimeMillis();
                System.out.println("运行时间：" + String.valueOf(endTime - startTime) + "ms");
            }
            return files;
        }else{
            throw new Exception("file is not null. 文件不能为空");
        }
    }

    @Override
    public List<SysFile> copy(List<CopyFile> files) throws IOException {
        List<SysFile> sysFiles = new ArrayList<>();
        for(CopyFile file : files){
            SysFile sysFile = super.selectByPk(file.getOldFileId());
            Path oldFile = Paths.get(sysFile.getPath());
            Path newFile = Paths.get(file.getNewPath() + file.getNewName());
            Files.copy(oldFile, newFile);

            sysFile.setName(file.getNewName());
            sysFile.setPath(file.getNewPath());
            sysFile.setCreateTime(DateUtil.getDateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
            sysFile.setMigrationVersion(1);
            sysFile.setId(null);
            super.insert(sysFile);
            sysFiles.add(sysFile);
        }
        return sysFiles;
    }

    @Override
    public List<SysFile> move(List<CopyFile> files) throws IOException {
        List<SysFile> sysFiles = new ArrayList<>();
        for(CopyFile file : files){
            SysFile sysFile = super.selectByPk(file.getOldFileId());
            Long id = sysFile.getId();
            Path oldFile = Paths.get(sysFile.getPath());
            Path newFile = Paths.get(file.getNewPath() + file.getNewName());
            Files.move(oldFile, newFile);

            sysFile.setName(file.getNewName());
            sysFile.setPath(file.getNewPath());
            sysFile.setCreateTime(DateUtil.getDateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
            sysFile.setMigrationVersion(1);
            super.insert(sysFile);
            super.deleteByPk(id);
            sysFiles.add(sysFile);
        }
        return sysFiles;
    }

    @Override
    public List<SysFile> delete(List<Long> ids) throws IOException {
        List<SysFile> sysFiles = new ArrayList<>();
        for(Long id : ids){
            SysFile sysFile = super.selectByPk(id);
            Path oldFile = Paths.get(sysFile.getPath());
            Files.delete(oldFile);
            sysFile.setIsDel("1");
            sysFile.setMigrationVersion(sysFile.getMigrationVersion()+1);
            super.deleteByPk(id);
            sysFiles.add(sysFile);
        }
        return sysFiles;
    }

    protected final File createFile(MultipartFile file, String filePath) throws IOException {
        InputStream inputStream = file.getInputStream();
        ImageInputStream iis = ImageIO.createImageInputStream(inputStream);
        Iterator<ImageReader> iters = ImageIO.getImageReaders(iis);
        if (!iters.hasNext()) {
            throw new RuntimeException("请上传图片!!!!!");
        }
        if (file != null) {
            String timeNow = DateUtil.formatDateTime(new Date(), "yyyyMMdd");
            String filename = file.getOriginalFilename();
            String ext = null;
            if (filename.contains(".")) {
                ext = filename.substring(filename.lastIndexOf("."));
            } else {
                ext = "";
            }
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String path = filePath + File.separator + timeNow + File.separator + uuid + ext;
            log.info("path:{}", path);
            File targetFile = new File(path);
            targetFile.getParentFile().mkdirs();
            targetFile.createNewFile();
            //上传
            file.transferTo(targetFile);
            return targetFile;
        }
        return null;
    }

    /**
     * 保存文件信息到数据库
     *
     * @param file
     * @return
     */
    private SysFile saveMassage(File file,String mark) throws Exception {
        SysFile sysFile = null;
        try {
            sysFile = new SysFile();
            sysFile.setName(file.getName());
            sysFile.setPath(file.getPath());
            sysFile.setMark(mark);
            sysFile.setSize(Long.toString(file.length()));
            sysFile.setCreateTime(DateUtil.getDateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
            sysFile.setMigrationVersion(1);
            sysFile.setIsDel("0");
            int i = sysFileMapper.insertSelective(sysFile);
            if(i == 0){
                throw new Exception("信息保存失败!!");
            }
        } catch (Exception e) {
            throw new Exception("信息保存失败!!");
        }
        return sysFile;
    };
}
